package com.fly.core.job;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ThreadJob
{
    public final String DIR_PATH = getUploadFilePath();
    
    @Autowired
    ExecutorService fixedThreadPool;
    
    /**
     * 无默认值会抛出IllegalArgumentException
     */
    @Value("${welcome.msg:hello, 00fly!\n}")
    private String welcome;
    
    /**
     * 测试log.error
     */
    @Scheduled(initialDelay = 30 * 60000L, fixedDelay = 30 * 60000L)
    public void logError()
    {
        fixedThreadPool.execute(() -> {
            log.info("fixedThreadPool: {}", welcome);
            try
            {
                // 时间戳做文件名
                String fileName = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd/HH");
                File file = new File(DIR_PATH + fileName);
                file.getParentFile().mkdirs();
                FileUtils.writeStringToFile(file, welcome, StandardCharsets.UTF_8, true);
            }
            catch (IOException e)
            {
                log.error("保存文件失败", e.getCause());
            }
        });
    }
    
    /**
     * 获取保存文件的位置,相对于jar所在目录的路径
     *
     * @return
     */
    private String getUploadFilePath()
    {
        try
        {
            return new File("upload").getCanonicalPath() + "/";
        }
        catch (IOException e)
        {
            log.error("获取文件路径失败", e.getCause());
            return null;
        }
    }
}
